import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../data/services/data_management_service.dart';

/// 数据库连接测试组件
/// 用于测试数据库连接配置是否有效
class DbTestWidget extends ConsumerStatefulWidget {
  final Map<String, dynamic> connectionConfig;
  final VoidCallback? onTestSuccess;
  final Function(String)? onTestFailure;

  const DbTestWidget({
    super.key,
    required this.connectionConfig,
    this.onTestSuccess,
    this.onTestFailure,
  });

  @override
  ConsumerState<DbTestWidget> createState() => _DbTestWidgetState();
}

class _DbTestWidgetState extends ConsumerState<DbTestWidget> {
  bool _isTesting = false;
  String? _testResult;
  bool? _isConnected;

  /// 测试数据库连接
  Future<void> _testConnection() async {
    setState(() {
      _isTesting = true;
      _testResult = null;
      _isConnected = null;
    });

    try {
      final dataManagementService = DataManagementService();
      final bool isConnected =
          await dataManagementService.testConnection(widget.connectionConfig);

      setState(() {
        _isTesting = false;
        _isConnected = isConnected;
        _testResult = isConnected ? '连接成功' : '连接失败';
      });

      if (isConnected) {
        widget.onTestSuccess?.call();
      } else {
        widget.onTestFailure?.call('数据库连接失败');
      }
    } catch (e) {
      setState(() {
        _isTesting = false;
        _isConnected = false;
        _testResult = '测试失败: ${e.toString()}';
      });

      widget.onTestFailure?.call('测试失败: ${e.toString()}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.all(16),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SelectableText(
              '数据库连接测试结果',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),

            // 测试结果
            if (_testResult != null)
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: _isConnected == true
                      ? Colors.green.withValues(alpha: 0.1)
                      : Colors.red.withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(
                    color: _isConnected == true
                        ? Colors.green.withValues(alpha: 0.3)
                        : Colors.red.withValues(alpha: 0.3),
                  ),
                ),
                child: Row(
                  children: [
                    Icon(
                      _isConnected == true ? Icons.check_circle : Icons.error,
                      color: _isConnected == true ? Colors.green : Colors.red,
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: SelectableText(
                        _testResult!,
                        style: TextStyle(
                          color:
                              _isConnected == true ? Colors.green : Colors.red,
                        ),
                      ),
                    ),
                  ],
                ),
              ),

            if (_testResult != null) const SizedBox(height: 16),

            // 测试按钮
            Row(
              children: [
                ElevatedButton(
                  onPressed: _isTesting ? null : _testConnection,
                  child: _isTesting
                      ? const Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(
                              width: 16,
                              height: 16,
                              child: CircularProgressIndicator(strokeWidth: 2),
                            ),
                            SizedBox(width: 8),
                            SelectableText('测试中...'),
                          ],
                        )
                      : const SelectableText('测试连接'),
                ),
                if (_isTesting) const SizedBox(width: 16),
                if (_isTesting)
                  const SelectableText(
                    '正在测试数据库连接...',
                    style: TextStyle(
                      color: Colors.grey,
                    ),
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
